/** 
*
* @author  jiwf 
* @date 创建时间：2016年10月24日 下午4:50:29 
* @version 1.0 
* @since  
*  
*/
package com.xbstar.web;


import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.socket.TextMessage;

import com.google.gson.GsonBuilder;
import com.xbstar.bean.MsgInfo;
import com.xbstar.bean.SessionInfo;
import com.xbstar.bean.UserInfo;
import com.xbstar.bean.UserToSessionRela;
import com.xbstar.dao.MsgInfoRepository;
import com.xbstar.dao.SessionRepostitory;
import com.xbstar.dao.UserInfoRepository;
import com.xbstar.dao.UserToSessionRelaRepository;
import com.xbstar.tools.Timer;
import com.xbstar.websocket.MyWebSocketHandler;

@RestController
@RequestMapping("/msg")
public class MsgController {
	@Autowired
	SessionRepostitory sessionRe;
	@Autowired
	UserToSessionRelaRepository user2SessionRe;
	@Autowired
	MsgInfoRepository msgRe;
	@Autowired
	UserInfoRepository userRe;
	@Autowired
	DataSource dataSource;
	@Resource
	MyWebSocketHandler webSocket;
	@RequestMapping("/getall")
	public String getAllMsgGroup(@RequestParam("sessionId")Long sessionId){
		JSONObject json=new JSONObject();
		JSONArray tarray=new JSONArray();
		String sql="SELECT id,content,fromUserId,sendTime,userName,headImgUrl,nikeName,affixBelongTo from msguserview WHERE sessionId=?";
		try {
			Connection conn=dataSource.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setLong(1, sessionId);
			 ResultSet rs = ps.executeQuery();
			 while (rs.next()) {
				 JSONObject ajson=new JSONObject();
				 ajson.put("id", rs.getString("id"));
				 ajson.put("nikeName", rs.getString("nikeName"));
				 ajson.put("sendTime", rs.getString("sendTime"));
				 ajson.put("content", rs.getString("content"));
				 ajson.put("headImgUrl", rs.getString("headImgUrl"));
				 tarray.put(ajson);
			}
			 json.put(UserPackage.STATUS, UserPackage.SUCCESS);
			 json.put(UserPackage.DATA, tarray);
		} catch (Exception e) {
			e.printStackTrace();
			 json.put(UserPackage.STATUS, UserPackage.SERVER_ERROR);
		}
		
		return json.toString();
	}
	@RequestMapping("/findallbyuser")
	public String findAllSessionMsgByUserId(@RequestParam("userId")Long userId){
		JSONObject json=new JSONObject();
		//1.先获取广播的消息
		//2.获取所有会话信息
		//3.获取该会话下的消息
		JSONArray array=new JSONArray();
		
		//1 TODO
		
		
		//2.
		
		List<UserToSessionRela>user2sesArr=	user2SessionRe.findByUserId(userId);
		if(user2sesArr==null||user2sesArr.isEmpty()){
			json.put(UserPackage.STATUS, UserPackage.EMPTY);
			return json.toString();
		}
		try {
			Connection conn = dataSource.getConnection();
			user2sesArr.parallelStream().forEach(item->{
				if(item.getSessionBelongTo()==null)return;
				Long sessionId;
				SessionInfo ssinfo=	sessionRe.findTop1BySessionBelongTo(item.getSessionBelongTo());
				if(ssinfo!=null){
					sessionId=ssinfo.getId();
				}else{
					return;
				}
				JSONObject tjson=new JSONObject();
				String sessionsql="SELECT id,sessionName,url,userImgUrl from sessionaffixview WHERE id=?";
				String sql="SELECT id,content,fromUserId,sendTime,headImgUrl,nikeName from msguserview WHERE sessionId=?";
				try {
					JSONArray tarray=new JSONArray();
					PreparedStatement ps1 = conn.prepareStatement(sessionsql);
					ps1.setLong(1, sessionId);
					 ResultSet rs1 = ps1.executeQuery();
					 JSONObject ajson=new JSONObject();
					 while (rs1.next()) {
						 ajson.put("id", rs1.getString("id"));
						 ajson.put("name", rs1.getString("sessionName"));
						 ajson.put("imgUrl", rs1.getString("url")==null?(rs1.getString("userImgUrl")==null?"11":rs1.getString("userImgUrl")):rs1.getString("url"));
					}
					 rs1.close();
					 ps1.close();
					PreparedStatement ps = conn.prepareStatement(sql);
					ps.setLong(1, sessionId);
					 ResultSet rs = ps.executeQuery();
					 while (rs.next()) {
						 JSONObject bjson=new JSONObject();
						 bjson.put("msgId", rs.getString("id"));
						 bjson.put("nikeName", rs.getString("nikeName"));
						 bjson.put("sendTime", rs.getString("sendTime"));
						 bjson.put("content", rs.getString("content"));
						 Long userno=rs.getLong("fromUserId");
						 bjson.put("isFromMe",userId.equals(userno));
						 bjson.put("headImgUrl", rs.getString("headImgUrl"));
						 tarray.put(bjson);
					}
					 rs.close();
					 ps.close();
					 ajson.put("msgs", tarray);
					 array.put(ajson);
				} catch (Exception e) {
					e.printStackTrace();
				}
			});
			conn.close();
			json.put(UserPackage.STATUS, UserPackage.SUCCESS);
			json.put(UserPackage.DATA, array);
		} catch (Exception e1) {
			e1.printStackTrace();
			json.put(UserPackage.STATUS, UserPackage.SERVER_ERROR);
		}
		 
		return json.toString();
	}
	@RequestMapping("/tosession")
	public String sendMsgTosession(@RequestParam("userId")Long userId,@RequestParam("sessionId")Long sessionId,@RequestParam("content")String content){
		JSONObject json =new JSONObject();
		//需要返回user nickname，headimgurl，msgid
		MsgInfo msg=new MsgInfo();
		msg.setContent(content);
		msg.setFromUserId(userId);
		msg.setToUserId(sessionId);
		msg.setSendTime(Timer.getCurrentString());
	    msg=msgRe.save(msg);
	    JSONObject tjson =new JSONObject();
	    tjson.put("msgId", msg.getId());
	    UserInfo user=userRe.findOne(userId);
	    tjson.put("nikeName", user.getNickName());
	    tjson.put("headImgUrl", user.getHeadImgUrl());
	    tjson.put("content", content);
	    tjson.put("isFromMe", false);
	    tjson.put("sendTime", msg.getSendTime());
	    tjson.put("sessionId", sessionId);
	    //通过websocket发出
	    try {
			String sessionsql="SELECT id,sessionName,url,userImgUrl from sessionaffixview WHERE id=?";
				Connection conn=dataSource.getConnection();
				PreparedStatement ps1 = conn.prepareStatement(sessionsql);
				ps1.setLong(1, sessionId);
				 ResultSet rs1 = ps1.executeQuery();
				 JSONObject ajson=new JSONObject();
				 while (rs1.next()) {
					 ajson.put("sessionName", rs1.getString("sessionName"));
					 ajson.put("imgUrl", rs1.getString("url")==null?(rs1.getString("userImgUrl")==null?"11":rs1.getString("userImgUrl")):rs1.getString("url"));
				}
			 SessionInfo  session=sessionRe.findOne(sessionId);
			 if(session.getSessionBelongTo()==null){
				 json.put("status", "500");
				 return json.toString();
			 }
	    	List<UserToSessionRela>user2sesArr=	user2SessionRe.findBySessionBelongTo(session.getSessionBelongTo());
	    	user2sesArr.parallelStream().forEach(item->{
	    		if(item.getUserId()!=userId){
	    			try {
						webSocket.sendMessageToUser(item.getUserId(),new TextMessage(tjson.toString()));
					} catch (Exception e) {
						e.printStackTrace();
					}
	    		}
	    	});
		} catch (Exception e) {
			e.printStackTrace();
		}
	    tjson.put("isFromMe", true);
	    json.put("status", "200");
	    json.put("data", tjson);
		return json.toString();
	}
	@RequestMapping("/broadcast")
	public String broadcast(@RequestParam("content")String content){
		JSONObject json=new JSONObject();
		JSONObject tjson=new JSONObject();
		tjson.put("msgId", "broadcast");
		tjson.put("sessionId", "broadcast");
		  tjson.put("nikeName", "管理员");
		    tjson.put("headImgUrl", "11");
		    tjson.put("content", content);
		    tjson.put("isFromMe", false);
		    tjson.put("sendTime", Timer.getCurrentString());
		    tjson.put("sessionName", "广播");
		try {
			webSocket.broadcast(new TextMessage(tjson.toString()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		json.put("status", "200");
		return json.toString();
	}
}
